package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.UserCartAddUuBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_UserCartAddUuWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_UserCartAddUuWindow().init(
                4005,
                2,
                "Dws_UserCartAddUuWindow",
                Constant.TOPIC_DWD_USER_CART_ADD
        );
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //TODO 转成POJO
        SingleOutputStreamOperator<UserCartAddUuBean> beanStream = parseToPojo(stream);
        //TODO 开窗聚合
        SingleOutputStreamOperator<UserCartAddUuBean> resultStream = windowAndAgg(beanStream);
        //TODO 写入到 clickhouse
        writeToClickHouse(resultStream);
    }

    private void writeToClickHouse(SingleOutputStreamOperator<UserCartAddUuBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_cart_add_uu_window", UserCartAddUuBean.class));
    }

    private SingleOutputStreamOperator<UserCartAddUuBean> windowAndAgg(SingleOutputStreamOperator<UserCartAddUuBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserCartAddUuBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserCartAddUuBean>() {
                                    @Override
                                    public long extractTimestamp(UserCartAddUuBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<UserCartAddUuBean>() {
                            @Override
                            public UserCartAddUuBean reduce(UserCartAddUuBean value1, UserCartAddUuBean value2) throws Exception {
                                value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<UserCartAddUuBean, UserCartAddUuBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx, Iterable<UserCartAddUuBean> elements, Collector<UserCartAddUuBean> out) throws Exception {
                                UserCartAddUuBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<UserCartAddUuBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(new KeySelector<JSONObject, String>() {
                    @Override
                    public String getKey(JSONObject value) throws Exception {
                        return value.getString("ts");
                    }
                })
                .process(new KeyedProcessFunction<String, JSONObject, UserCartAddUuBean>() {
                    private ValueState<String> lastCartAddDateState;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastCartAddDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastCartAddDateState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<UserCartAddUuBean> out) throws Exception {
                        String lastCartAddDate = lastCartAddDateState.value();
                        long ts = value.getLong("ts") * 1000;
                        String today = AtguiguUtil.toDate(ts);

                        if (!today.equals(lastCartAddDate)) {
                            lastCartAddDateState.update(today);
                            out.collect(new UserCartAddUuBean("", "", 1L, ts));
                        }
                    }
                });

    }
}
